package neuralNetworks.tool;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import neuralNetworks.NeuralNetwork;
import neuralNetworks.Neuron;

public class NNetSaver<T extends NeuralNetwork<? extends Neuron>> {

	public void save(T nnet, String file) {
		try {
			if (file.lastIndexOf("/") > 0)
				new File(file.substring(0, file.lastIndexOf("/"))).mkdirs();
			BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(file));
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(nnet);
			oos.close();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public T load(String file) {
		try {
			FileInputStream fis = new FileInputStream(file);
			ObjectInputStream ois = new ObjectInputStream(fis);
			@SuppressWarnings("unchecked")
			T nnet = (T) ois.readObject();
			ois.close();
			fis.close();
			System.out.println("Net loaded");
			return nnet;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
